<?php

namespace Modules\Car\Http\Controllers;

use App\Helpers\PayTrait;
use App\Helpers\ResponseData;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Car\Entities\Mot;
use Modules\Car\Entities\RecognizeDrivingLicense;

//车辆年检控制器
class MotController extends Controller
{
    use ResponseData,PayTrait;
    public function list(Mot $mot,Request $request){
        $type = $request->input('type','');
        $car_id = $request->input('car_id','');
        if($type=='all'){
            $data = $mot->query()
                ->with('car')
                ->when($car_id,function($query)use($car_id){
                    $query->where('car_id',$car_id);
                })
                ->orderBy('id','desc')->get();
        }else{
            $size = $request->input('size',10);
            $data = $mot->query()
                ->with('car')
                ->when($car_id,function($query)use($car_id){
                    $query->where('car_id',$car_id);
                })
                ->orderBy('id','desc')->paginate($size);
        }
        return $this->success($data);
    }
    public function store(Mot $mot,Request $request){
        $car = RecognizeDrivingLicense::query()->find($request->car_id);
        if($car){
            $data = $request->all();
            $model = $mot->query()->create($data);
            if($model){
                $this->changeLimitYear($model->car_id,'mots_end',$model->limit_year);
            }
            return $this->success('保存成功');
        }else{
            return $this->failed('车辆不存在',201);
        }
    }
    public function edit(Mot $mot,Request $request){
        $data = $mot->find($request->id);
        return $this->success($data);
    }
    public function update(Mot $mot,Request $request){
        $data = $mot->find($request->id);
        $data->update($request->all());
        if($request->filled('limit_year')){//年检完成
            //变更年检状态、变更年检下次时间
            $this->changeLimitYear($data->car_id,'mots_end',$request->limit_year);
        }
        return $this->success('修改成功');
    }
    public function destory(Mot $mot,Request $request){
        $data = $mot->find($request->id);
        $data->delete();
    }
}
